//
//  ALOauthViewController.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/10.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
import SVProgressHUD

class ALOauthViewController: UIViewController {
//设置webView加载网页界面
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {

        super.viewDidLoad()
//        webView的viewColor的颜色默认是白色
//        view.backgroundColor = viewBgColor
        // Do any additional setup after loading the view.
//        设置导航栏左右按钮
        setNavgationBar()
//        用webview请求网络数据
        requsetNetWork()
    }
    private func requsetNetWork(){
    
        let url = connectURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
//        添加指示器
        SVProgressHUD.showWithStatus("正在加载")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
//
    }
    
//    拼接url
    /// 拼接Oauth授权登录界面的url（GET）

    private func connectURL() -> NSURL{
//https://api.weibo.com/oauth2/authorize?client_id=540072961&redirect_uri=http://www.baidu.com/
        let urlString: String = oauthURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        return NSURL(string: urlString)!
    }
    private func setNavgationBar(){
//    左边的填充按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(UIColor.setFill))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(NSProgress.cancel))
    }
    
//    MARK: - 按钮的点击事件
    @objc private func setFill(){

        let js = "document.getElementById('userId').value = '291265024@qq.com';document.getElementById('passwd').value = '281155'"
        
//        用webView进行登录
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    @objc private func cancel(){
        SVProgressHUD.dismiss()
//    将modal出来的控制器进行dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }

//    懒加载webView
    lazy var webView = UIWebView()
}
//类的延展:设置webView的代理方法
extension ALOauthViewController:UIWebViewDelegate{
//实现代理方法
//    下面的方法是webView在开始加载的时候,判断是否加载网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        let isRedirectURL = urlString!.hasPrefix(redirect_uri)
        
        if !isRedirectURL {
            return true
        }else{
        //授权回掉地址,点击的是取消或者授权
//            判断点击的是取消还是授权,如果?后面的是code= 开头就是授权按钮
//            query是get请求?后面的东西
            let query = request.URL?.query
            

            let codeString = "code="
            if query!.hasPrefix(codeString) {
//                进入内部表示是授权按钮
//                截取字符串转换为NSString
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)

                ALUserAccountViewModel.userAccountViewModel.loadAccessToken(code,loadAcessTokenSuccessCallBack:{
                (error) -> () in
                    if error != nil{
                    print("加载失败了:\(error)")
                        SVProgressHUD.showErrorWithStatus("网络加载超时")
//                        延时关闭控制器
                        // 延时关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.cancel()
                            
//                            TODO:在此处要跳转新的控制器
                            
                        })
                    }
//                    切换界面
                    let controller = ALWelcomeController()
                    (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(controller)
//                    print("加载AccessToken成功了")
                    self.cancel()
                } )
            }else{
            
//                点击取消按钮后直接退出控制器
                cancel()
            }
            return false
        }
        
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//        ALPrint(error?.code)
        if error?.code==102 {
            return
        }
        SVProgressHUD.showErrorWithStatus("网络不给力...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
}
